package org.shop.weixin.servlet;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.codec.digest.DigestUtils;
import org.shop.weixin.pojo.SNSUserInfo;
import org.shop.weixin.util.AdvancedUtil;
import org.shop.weixin.util.EmojiFilterUtils;
import org.shop.weixin.util.WeixinOauth2Token;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * 授权后的回调请求处理 主要功能是解决送水工扫描二维码后生成自己的帐号信息
 * 注册地址：https://open.weixin.qq.com/connect/oauth2
 * /authorize?appid=wx682d126f39fac260
 * &redirect_uri=http://test.imimz.com/adminOAuth
 * .jhtml?shop=3&response_type=code
 * &scope=snsapi_userinfo&state=STATE#wechat_redirect
 * 
 * @author
 * @date 2013-11-12
 */
@Controller("adminOAuthController")
@RequestMapping("/adminOAuth")
public class adminOAuthServlet {
	
	@Value("${workerappid}")
	private String workerappid;
	@Value("${workerappsecret}")
	private String workerappsecret;


	@RequestMapping(method = RequestMethod.GET)
	public String doGet(HttpServletRequest request,
			HttpServletResponse response, ModelMap model, HttpSession session)
			throws ServletException, IOException {

		String code = request.getParameter("code");
		String shopId = request.getParameter("shop");
		System.out.println("code" + code);
		System.out.println((!"authdeny".equals(code)));
		//
		// 用户同意授权
		if (!"authdeny".equals(code)) {
			// 获取网页授权access_token
			System.out.println("codeToken" + code);
			WeixinOauth2Token weixinOauth2Token = AdvancedUtil
					.getOauth2AccessToken(workerappid,
							workerappsecret, code);
			// 网页授权接口访问凭证
			String accessToken = weixinOauth2Token.getAccessToken();
			System.out.println("accessToken" + accessToken);
			// 用户标识
			String openId = weixinOauth2Token.getOpenId();
			System.out.println("openId" + openId);
			// 获取用户信息
			SNSUserInfo snsUserInfo = AdvancedUtil.getSNSUserInfo(accessToken,
					openId);
			System.out.println("city" + snsUserInfo.getCity());
			System.out.println("openId:" + snsUserInfo.getOpenId());
			System.out.println("Nickname"
					+ EmojiFilterUtils.filterEmoji(snsUserInfo.getNickname()));
			
			/*重新如下代码：如果配送人员存在，跳转到错误页面。
			 * if (adminService.usernameExists(snsUserInfo.getOpenId())) {

				return "redirect:/error.html";

			};*/
			
			/**
			 * 跳转到配送人员主页
			 */
			return "redirect:/login.html";

		}
		/**跳转到未授权页面*/
		return null;
	}
}
